package com.ishare.common.handler;

import com.ishare.common.errorcode.ErrorCodeEnum;
import com.ishare.common.exception.BusinessException;
import com.ishare.common.wrapper.Wrapper;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 * 全局异常处理器
 * </p>
 *
 * @author xzl
 * @since 2020-01-16
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 参数非法异常.
     *
     * @param e the e
     * @return the wrapper
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<String> constraintViolationException(MethodArgumentNotValidException e) {
        log.error("参数非法异常===>{}", e.getMessage());
        return Wrapper.error(ErrorCodeEnum.VALIDATE_FAILED,
                e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 账号异常.
     *
     * @param e the e
     * @return the wrapper
     */
    @ExceptionHandler({LockedAccountException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<String> lockedAccountException(LockedAccountException e) {
        log.error("账号异常===>{}", e.getMessage());
        return Wrapper.error(ErrorCodeEnum.USER_ERROR_A0202,
                e.getMessage());
    }

    /**
     * token失效.
     *
     * @param e the e
     * @return the wrapper
     */
    @ExceptionHandler({IncorrectCredentialsException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<String> IncorrectCredentialsException(IncorrectCredentialsException e) {
        log.error("token失效===>{}", e.getMessage());
        return Wrapper.error(ErrorCodeEnum.USER_ERROR_A0311,
                e.getMessage());
    }

    /**
     * 业务异常
     *
     */
    @ExceptionHandler(BusinessException.class)
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<String> myException(BusinessException e) {
        log.error("业务异常===>{}", e.getMessage(), e);
        return Wrapper.error(e.getMessage());
    }

    /**
     * 全局异常
     *
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<Object> exception(Exception e) {
        log.error("全局异常===>{}", e.getMessage(), e);
        //可做入库处理
        return Wrapper.error();
    }

}
